package com.wxzz.elearing.course.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wxzz.elearing.course.dto.CurriculumSectionTopicIsPassDto;
import com.wxzz.elearing.course.entity.*;
import com.wxzz.elearing.course.mapper.*;
import com.wxzz.elearing.course.service.ICurriculumSectionTopicService;
import com.wxzz.elearing.course.service.openfeign.IWxUserApiFeign;
import com.wxzz.elearning.common.aop.Idempotent;
import com.wxzz.elearning.common.constants.RedisConstants;
import com.wxzz.elearning.common.exception.ServiceException;
import com.wxzz.elearning.common.vo.ReturnVO;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * <p>
 * 课程章节测评试题 服务实现类
 * </p>
 *
 * @author
 * @since 2021-03-10
 */
@Service
public class CurriculumSectionTopicServiceImpl extends ServiceImpl<CurriculumSectionTopicMapper, CurriculumSectionTopic> implements ICurriculumSectionTopicService {

    @Autowired
    private CurriculumSectionTopicMapper curriculumSectionTopicMapper;

    @Autowired
    private CurriculumSectionTopicAnswerMapper curriculumSectionTopicAnswerMapper;

    @Autowired
    private WxUserCurriculumSectionMapper wxUserCurriculumSectionMapper;

    @Override
    public ReturnVO<List<CurriculumSectionTopic>> listCurriculumSectionTopicByCurriculumSectionTopicId(Long curriculumSectionTopicId, Integer topicCategory) {
        List<CurriculumSectionTopic> curriculumSectionTopics = curriculumSectionTopicMapper.selectList(new LambdaQueryWrapper<CurriculumSectionTopic>()
                .eq(CurriculumSectionTopic::getCurriculumSectionId, curriculumSectionTopicId)
                .eq(CurriculumSectionTopic::getTopicCategory, topicCategory));
        for (CurriculumSectionTopic curriculumSectionTopic : curriculumSectionTopics) {
            //试题答案选项
            List<CurriculumSectionTopicAnswer> curriculumSectionTopicAnswers = curriculumSectionTopicAnswerMapper.selectList(new LambdaQueryWrapper<CurriculumSectionTopicAnswer>()
                    .eq(CurriculumSectionTopicAnswer::getCurriculumSectionTopicId, curriculumSectionTopic.getId()));
            curriculumSectionTopic.setCurriculumSectionTopicAnswerList(curriculumSectionTopicAnswers);
        }
        return new ReturnVO<>("测评试题查询成功", curriculumSectionTopics);
    }

    @Autowired
    private CurriculumSectionMapper curriculumSectionMapper;

    @Autowired
    private WxUserCurriculumDataMapper wxUserCurriculumDataMapper;

    @Idempotent
    @Override
    public ReturnVO curriculumSectionTopicIsPass(JSONObject jsonObject, CurriculumSectionTopicIsPassDto curriculumSectionTopicIsPassDto) {
        if (curriculumSectionTopicIsPassDto.getCurriculumSectionId() == null) {
            throw new ServiceException("请传入章节id");
        }
        if (curriculumSectionTopicIsPassDto.getCurriculumId() == null) {
            throw new ServiceException("请传入课程id");
        }
        BigDecimal allScore = new BigDecimal("0.00");
        //计算分数
        for (CurriculumSectionTopic curriculumSectionTopic : curriculumSectionTopicIsPassDto.getCurriculumSectionTopics()) {
            List<CurriculumSectionTopicAnswer> curriculumSectionTopicAnswers = curriculumSectionTopic.getCurriculumSectionTopicAnswerList();
            //取出答案
            for (CurriculumSectionTopicAnswer curriculumSectionTopicAnswer : curriculumSectionTopicAnswers) {
                //取出选项的分数
                if (Boolean.TRUE.equals(curriculumSectionTopicAnswer.getIsChoose())) {
                    if (curriculumSectionTopicAnswer.getScore() != null) {
                        allScore = allScore.add(curriculumSectionTopicAnswer.getScore());
                    }
                }
            }
        }


        WxUserCurriculumSection wxUserCurriculumSection = new WxUserCurriculumSection();
        //设置总分
        wxUserCurriculumSection.setAllScore(allScore);
        wxUserCurriculumSection.setCurriculumSectionId(curriculumSectionTopicIsPassDto.getCurriculumSectionId());
        wxUserCurriculumSection.setWxUserId(jsonObject.getLong("id"));
        wxUserCurriculumSection.setUseTime(curriculumSectionTopicIsPassDto.getUseTime());
        wxUserCurriculumSection.setEnterpriseId(jsonObject.getLong("enterpriseId"));
        wxUserCurriculumSection.setCurriculumId(curriculumSectionTopicIsPassDto.getCurriculumId());
        //验证是否通过
        CurriculumSection curriculumSection = curriculumSectionMapper.selectById(curriculumSectionTopicIsPassDto.getCurriculumSectionId());
        if (curriculumSection == null) {
            throw new ServiceException("该章节已经不存在");
        } else {
            if (wxUserCurriculumSection.getAllScore().compareTo(curriculumSection.getQualified()) == 1 || wxUserCurriculumSection.getAllScore().compareTo(curriculumSection.getQualified()) == 0) {
                //如果总分数大于等于合格分数
                wxUserCurriculumSection.setIsPass(1);
                //查询用户完成的章节
                Integer pass = wxUserCurriculumSectionMapper.selectCount(new LambdaQueryWrapper<WxUserCurriculumSection>()
                        .eq(WxUserCurriculumSection::getWxUserId, jsonObject.getLong("id"))
                        .eq(WxUserCurriculumSection::getCurriculumSectionId, curriculumSection.getId())
                        .eq(WxUserCurriculumSection::getIsPass, 1));
                //如果第一次通过 则累计完成总课时 以及该用户对应该课的课时
                if (pass == 0) {
                    //累计总课时
                    WxUserCurriculumData wxUserCurriculumData = wxUserCurriculumDataMapper.selectOne(new LambdaQueryWrapper<WxUserCurriculumData>()
                            .eq(WxUserCurriculumData::getWxUserId, jsonObject.getLong("id")));
                    if (wxUserCurriculumData == null) {
                        //如果不存在则添加用户数据
                        WxUserCurriculumData insert = new WxUserCurriculumData();
                        insert.setWxUserId(jsonObject.getLong("id"));
                        insert.setFinishClass(1L);
                        insert.setStudyTime(curriculumSection.getVideoTime());
                        insert.setTodayStudyTime(curriculumSection.getVideoTime());
                        insert.setEnterpriseId(jsonObject.getLong("enterpriseId"));
                        wxUserCurriculumDataMapper.insert(insert);
                    } else {
                        //如果存在数据则累计
                        wxUserCurriculumData.setFinishClass(wxUserCurriculumData.getFinishClass() + 1);
                        wxUserCurriculumData.setStudyTime(wxUserCurriculumData.getTodayStudyTime() + curriculumSection.getVideoTime());
                        wxUserCurriculumData.setTodayStudyTime(wxUserCurriculumData.getTodayStudyTime() + curriculumSection.getVideoTime());
                        wxUserCurriculumData.setEnterpriseId(jsonObject.getLong("enterpriseId"));
                        wxUserCurriculumDataMapper.updateById(wxUserCurriculumData);
                    }
                    //查询当天累计用户对应该课课时
                    WxUserCurriculumStatisticsData wxUserCurriculumStatisticsData = wxUserCurriculumStatisticsDataMapper.selectOne(new LambdaQueryWrapper<WxUserCurriculumStatisticsData>()
                            .eq(WxUserCurriculumStatisticsData::getWxUserId, jsonObject.getLong("id"))
                            .eq(WxUserCurriculumStatisticsData::getEnterpriseId, jsonObject.getLong("enterpriseId"))
                            .eq(WxUserCurriculumStatisticsData::getCurriculumId, curriculumSectionTopicIsPassDto.getCurriculumId())
                            .eq(WxUserCurriculumStatisticsData::getSaveTime, LocalDate.now().toString()));
                    if (wxUserCurriculumStatisticsData == null) {
                        //如果不存在则添加用户数据
                        WxUserCurriculumStatisticsData insert = new WxUserCurriculumStatisticsData();
                        insert.setWxUserId(jsonObject.getLong("id"));
                        insert.setFinishClass(1L);
                        insert.setStudyTime(curriculumSection.getVideoTime());
                        insert.setEnterpriseId(jsonObject.getLong("enterpriseId"));
                        insert.setCurriculumId(curriculumSectionTopicIsPassDto.getCurriculumId());
                        insert.setSaveTime(LocalDate.now().toString());
                        wxUserCurriculumStatisticsDataMapper.insert(insert);
                    } else {
                        //如果存在数据则累计
                        wxUserCurriculumStatisticsData.setFinishClass(wxUserCurriculumStatisticsData.getFinishClass() + 1);
                        wxUserCurriculumStatisticsData.setStudyTime(wxUserCurriculumStatisticsData.getStudyTime() + curriculumSection.getVideoTime());
                        wxUserCurriculumStatisticsDataMapper.updateById(wxUserCurriculumStatisticsData);
                    }
                }
                //将观看进度归零
                redisTemplate.opsForValue().set(RedisConstants.CURRICULUM_LAST_SEE_TIME + jsonObject.getLong("id") + ":" + curriculumSection.getCurriculumId(), 0 + ":" + 0);
            } else {
                wxUserCurriculumSection.setIsPass(0);
            }
        }
        wxUserCurriculumSectionMapper.insert(wxUserCurriculumSection);
        return new ReturnVO<>("测试完毕", wxUserCurriculumSection);
    }

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private WxUserCurriculumStatisticsDataMapper wxUserCurriculumStatisticsDataMapper;
//    @Override
//    public ReturnVO curriculumSectionTopicIsPass(Long wxUserId, CurriculumSectionTopicIsPassDto curriculumSectionTopicIsPassDto) {
//        if (curriculumSectionTopicIsPassDto.getCurriculumSectionId() == null) {
//            throw new ServiceException("请传入课程章节id");
//        }
//        //二次验证是否通过
//        CurriculumSection curriculumSection = curriculumSectionMapper.selectById(curriculumSectionTopicIsPassDto.getCurriculumSectionId());
//        if (curriculumSection == null) {
//            throw new ServiceException("该章节已经不存在");
//        } else {
//            if (curriculumSectionTopicIsPassDto.getAllScore().compareTo(curriculumSection.getQualified()) == 1) {
//                //如果总分数大于合格分数
//                curriculumSectionTopicIsPassDto.setIsPass(1);
//            }else {
//                curriculumSectionTopicIsPassDto.setIsPass(0);
//            }
//        }
//        Optional<WxUserCurriculumSection> wxUserCurriculumSectionOptional = wxUserCurriculumSectionMapper.selectWxUserCurriculumSection(curriculumSectionTopicIsPassDto.getCurriculumSectionId(), wxUserId);
//        //如果存在测试记录
//        wxUserCurriculumSectionOptional.ifPresent(wxUserCurriculumSection -> {
//            wxUserCurriculumSection.setAllScore(curriculumSectionTopicIsPassDto.getAllScore());
//            wxUserCurriculumSection.setUseTime(curriculumSectionTopicIsPassDto.getUseTime());
//            //设置测试通过
//            if (wxUserCurriculumSection.getIsPass() == 0 && curriculumSectionTopicIsPassDto.getIsPass() == 1) {
//                wxUserCurriculumSection.setIsPass(1);
//            }
//            if (curriculumSectionTopicIsPassDto.getIsPass() == 0) {
//                wxUserCurriculumSection.setNotPassNum(wxUserCurriculumSection.getNotPassNum() + 1);
//            }
//            wxUserCurriculumSection.setTestNum(wxUserCurriculumSection.getTestNum() + 1);
//            wxUserCurriculumSectionMapper.updateById(wxUserCurriculumSection);
//        });
//        int insert = 0;
//        //不存在测试记录
//        if (!wxUserCurriculumSectionOptional.isPresent()) {
//            WxUserCurriculumSection wxUserCurriculumSection = new WxUserCurriculumSection();
//            if (curriculumSectionTopicIsPassDto.getIsPass() == 0) {
//                wxUserCurriculumSection.setNotPassNum(1L);
//            }
//            wxUserCurriculumSection.setTestNum(1L);
//            wxUserCurriculumSection.setAllScore(curriculumSectionTopicIsPassDto.getAllScore());
//            wxUserCurriculumSection.setUseTime(curriculumSectionTopicIsPassDto.getUseTime());
//
//            insert = wxUserCurriculumSectionMapper.insert(wxUserCurriculumSection);
//        }
//        return new ReturnVO<>("测试完毕", insert);
//    }
}
